/*
 * @Author: maskMan
 * @LastEditTime: 2024-10-17 19:06:47
 * @Descripttion:存储管理
 */
import { STORAGE_KEY } from './constants'
import { util } from './util'
function _decorator(target: typeof CacheStorage) {
  target._readData()
}
@_decorator
export default class CacheStorage {
  static _publicData = {} //公共数据
  static _userData = {} //用户数据
  static _configData = {} //配置数据
  static _redordData = {} //记录数据
  /**初始化读取存储 */
  static _readData() {
    for (let i = 0; i < cc.sys.localStorage.length; i++) {
      const key: string = cc.sys.localStorage.key(i)
      try {
        const ret = cc.sys.localStorage.getItem(key)
        if (ret) {
          if (key == STORAGE_KEY.CONFIG) {
            this._configData = JSON.parse(ret)
          } else if (key == STORAGE_KEY.PUBLIC) {
            this._publicData = JSON.parse(ret)
          } else if (key == STORAGE_KEY.USER) {
            this._userData = JSON.parse(ret)
          } else if (key == STORAGE_KEY.RECORD) {
            this._redordData = JSON.parse(ret)
          }
        }
      } catch (err) {
        console.error('缓存读取出错', err)
      }
    }
  }
  /**
   * @description:删除存储数据
   * @param {string} key 存储键
   * @return {*}
   */
  static delData(key: string, mark: STORAGE_KEY) {
    if (mark == STORAGE_KEY.CONFIG) {
      delete this._configData[key]
      cc.sys.localStorage.setItem(mark, JSON.stringify(this._configData))
    } else if (mark == STORAGE_KEY.PUBLIC) {
      delete this._publicData[key]
      cc.sys.localStorage.setItem(mark, JSON.stringify(this._publicData))
    } else if (mark == STORAGE_KEY.USER) {
      delete this._userData[key]
      cc.sys.localStorage.setItem(mark, JSON.stringify(this._userData))
    } else if (mark == STORAGE_KEY.RECORD) {
      delete this._redordData[key]
      cc.sys.localStorage.setItem(mark, JSON.stringify(this._redordData))
    }
  }
  /**
   * @description:清理缓存数据
   * @param {string} key 存储键
   * @return {*}
   */
  static clearData(mark?: STORAGE_KEY) {
    if (!mark) {
      this._configData = {}
      this._publicData = {}
      this._userData = {}
      this._redordData = {}
      cc.sys.localStorage.clear()
      return
    }
    if (mark == STORAGE_KEY.CONFIG) {
      this._configData = {}
    } else if (mark == STORAGE_KEY.PUBLIC) {
      this._publicData = {}
    } else if (mark == STORAGE_KEY.USER) {
      this._userData = {}
    } else if (mark == STORAGE_KEY.RECORD) {
      this._redordData = {}
    }
    cc.sys.localStorage.removeItem(mark)
  }
  /**
   * @description:设置公共存储数据
   * @param {string} key 键名
   * @param {any} value 键值
   */
  static setPublicData(key: string, value: any) {
    try {
      const mark = STORAGE_KEY.PUBLIC
      this._publicData[key] = value
      cc.sys.localStorage.setItem(mark, JSON.stringify(this._publicData))
    } catch (error) {
      console.error('缓存设置出错', error)
    }
  }
  /**
   * @description:设置用户存储数据
   * @param {string} uid 用户ID
   * @param {Obj} user 用户信息
   */
  static setUserData(uid: string, user: Obj) {
    try {
      const mark = STORAGE_KEY.USER
      this._userData[uid] = user
      cc.sys.localStorage.setItem(mark, JSON.stringify(this._userData))
    } catch (error) {
      console.error('缓存设置出错', error)
    }
  }
  /**
   * @description:设置配置存储数据
   * @param {string} key 配置键
   * @param {Obj} data 配置数据
   */
  static setConfigData(key: string, data: any) {
    try {
      const mark = STORAGE_KEY.CONFIG
      this._configData[key] = data
      cc.sys.localStorage.setItem(mark, JSON.stringify(this._configData))
    } catch (error) {
      console.error('缓存设置出错', error)
    }
  }
  /**
   * @description:获取用户数据
   * @param {string} key 键名
   */
  static getPublicData(key?: string): any {
    try {
      const result = key ? this._publicData[key] : this._publicData
      return result || null
    } catch (error) {
      return null
    }
  }
  /**
   * @description:获取配置数据
   * @param {string} key 键名
   */
  static getConfigData(key?: string): any {
    try {
      const result = key ? this._configData[key] : this._configData
      return result || null
    } catch (error) {
      return null
    }
  }
  /**
   * @description:获取用户数据
   * @param {string} uid 用户id
   */
  static getUserData(uid?: string): Obj | Obj[] {
    try {
      if (uid) {
        return this._userData[uid] || null
      }
      return util.objectToArray(this._userData)
    } catch (error) {
      console.error('获取缓存出错', error)
      return null
    }
  }
  /**
   * @description:获取用户数据列表
   */
  static getUserList(): any[] {
    try {
      const list = []
      for (const k in this._userData) {
        if (this._userData[k]?.record?.length) {
          list.push(this._userData[k])
        }
      }
      return list
    } catch (error) {
      return null
    }
  }
  /**
   * @description:获取用户记录信息
   * @param {string} key 键名
   */
  static getUserRecord(key: string): IUserScore[] {
    const mark = `${key}`
    try {
      if (this._userData[mark]) {
        return this._userData[mark]['record'] || []
      }
      return []
    } catch (error) {
      return []
    }
  }
  /**
   * @description:设置存储用户记录信息
   * @param {string} key 键名
   * @param {any} value 键值
   */
  static setUserRecord(key: string, value: IUserScore): IUserInfo {
    const mark = `${key}`
    try {
      if (this._userData[mark]) {
        if (!this._userData[mark]['record']) {
          this._userData[mark]['record'] = []
        }
        this._userData[mark]['record'].push(value)
        const list: IUserScore[] = this._userData[mark]['record']
        let maxScore = 0
        let costTime = 0
        const keys = []
        for (let i = 0; i < list.length; i++) {
          const k = list[i].gamePath
          if (keys.includes(k) == false) {
            keys.push(k)
            maxScore += list[i].maxScore
          }
          costTime += list[i].trainTime
        }
        this._userData[mark].maxScore = maxScore
        this._userData[mark].trainTime = costTime
        cc.sys.localStorage.setItem(mark, JSON.stringify(this._userData[mark]))
        return this._userData[mark]
      }
      return null
    } catch (error) {
      delete this._userData[mark]
      return null
    }
  }
}
